import hashlib
import platform
import re

import psutil
import requests
import wmi

from one import OneNote
from profile import Profile
from xhs_utils.xhs_util import get_headers, get_params, js, check_cookies


class Home:
    def __init__(self, cookies=None):
        if cookies is None:
            self.cookies = check_cookies()
        else:
            self.cookies = cookies
        self.more_url = 'https://edith.xiaohongshu.com/api/sns/web/v1/user_posted'
        self.profile = Profile(self.cookies)
        self.oneNote = OneNote(self.cookies)
        self.headers = get_headers()
        self.params = get_params()

    # 主页
    def get_all_note_info(self, url):
        profile = self.profile.get_profile_info(url)
        note_id_list = []
        user_id = profile.userId
        cursor = ''
        self.params['user_id'] = user_id
        self.params['cursor'] = cursor
        while True:
            api = f"/api/sns/web/v1/user_posted?num=30&cursor={cursor}&user_id={user_id}&image_scenes="
            ret = js.call('get_xs', api, '', self.cookies['a1'])
            self.headers['x-s'], self.headers['x-t'] = ret['X-s'], str(ret['X-t'])
            response = requests.get(self.more_url, headers=self.headers, cookies=self.cookies, params=self.params)
            res = response.json()
            data = res["data"]
            if not data["notes"][0]:
                print(f"用户{user_id}没有笔记")
                break
            cursor, has_more, note_list = data["cursor"], data["has_more"], data["notes"]
            self.params['cursor'] = cursor
            for note in note_list:
                note_id_list.append(note['note_id'])
            if not has_more:
                break
        return note_id_list, profile

    # 主页
    def save_all_note_info(self, url, need_cover=False):
        profile = self.profile.save_profile_info(url)
        user_id = profile.userId
        cursor = ''
        self.params['user_id'] = user_id
        self.params['cursor'] = cursor
        index = 0
        while True:
            api = f"/api/sns/web/v1/user_posted?num=30&cursor={cursor}&user_id={user_id}&image_scenes="
            ret = js.call('get_xs', api, '', self.cookies['a1'])
            self.headers['x-s'], self.headers['x-t'] = ret['X-s'], str(ret['X-t'])
            response = requests.get(self.more_url, headers=self.headers, cookies=self.cookies, params=self.params)
            res = response.json()
            data = res["data"]
            if not data["notes"][0]:
                print(f"用户{user_id}没有笔记")
                break
            cursor, has_more, note_list = data["cursor"], data["has_more"], data["notes"]
            self.params['cursor'] = cursor
            for note in note_list:
                index += 1
                info = f'第{index}个笔记, '
                self.oneNote.save_one_note_info(self.oneNote.detail_url + note['note_id'], need_cover, info)
            if not has_more:
                break
        print(f'用户 {profile.nickname} 全部视频信息保存成功')

    def main(self, url_list):
        # url_list = [
        #     'https://www.xiaohongshu.com/user/profile/6185ce66000000001000705b',
        #     'https://www.xiaohongshu.com/user/profile/6034d6f20000000001006fbb',
        # ]
        for url in url_list:
            try:
                self.save_all_note_info(url)
            except:
                print(f'用户 {url} 查询失败')


def get_hardware_info():
    # 获取CPU信息（这里只是简单示例，可能需要进一步解析）
    info = {'cpu': psutil.cpu_count(logical=False)}

    # 获取磁盘信息（这里假设第一个磁盘包含序列号）
    disk_partitions = psutil.disk_partitions()
    if disk_partitions:
        # 注意：不是所有磁盘都有序列号，这里只是一个示例
        info['disk'] = disk_partitions[0].device  # 可能是UUID或其他标识符

    # Windows特有的WMI查询来获取主板序列号（如果可用）
    if platform.system() == 'Windows':
        c = wmi.WMI()
        for baseboard_id in c.Win32_BaseBoard():
            info['motherboard'] = baseboard_id.SerialNumber  # 主板序列号
            break  # 假设只有一个主板

    # 将所有信息组合成一个字符串，并生成哈希值作为硬件机器码
    hardware_id = ''.join(f'{k}:{v}' for k, v in info.items() if v)
    hash_object = hashlib.sha256(hardware_id.encode())
    hex_dig = hash_object.hexdigest()
    return hex_dig == "0fb01b6edf81f4dfad4fb125333256dadd2b22ea590d2d9d1571912dadd2d17c"


def is_url(input_string):
    """
    判断输入的字符串是否符合网址的基本格式。
    """
    # 网址的一般正则表达式 pattern，这个表达式并不是100%准确，但适用于大多数常见情况
    url_pattern = re.compile(
        r'http[s]?://'  # http:// 或 https://
        r'(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'  # 域名部分
        r'(?:/?|[/?]\\S+)$', re.IGNORECASE)  # 可选的路径部分
    return bool(url_pattern.match(input_string))


if __name__ == '__main__':
    if get_hardware_info():
        home = Home()
        while True:  # 无限循环，直到用户决定退出
            try:
                # 获取用户输入的数字
                uri = input("请输入要采集的主页（输入'q'退出）: ")
                # 检查用户是否想退出
                if uri.lower() == 'q':
                    break  # 退出循环
                if is_url(uri):
                    url_list = [str(uri)]
                    home.main(url_list)
                else:
                    print("输入不正确，请输入正确的主页URL")
            except ValueError:
                # 如果输入的不是整数，打印错误消息
                print("输入不正确，请重新输入。")
    else:
        print("ERROR...")
